#!/usr/bin/python3
import base64
import signal
import time
from hashlib import md5

from fastapi import FastAPI

import actor
import dto
from actor import syncActor, CopyRsp, GetCurDay
from dto import Response, CBResponse, QuantifyRequest

glb_salt = "33dfa95f-cb25-47c1-b4e0-1455998e720d"
actor.startActor()
app = FastAPI()


def stop_server(*args):
    actor.stopActor()


def verifyReq(req: QuantifyRequest) -> bool:
    now = int(time.time())
    diff = abs(now - req.noise)
    if diff >= 300:
        """"""
        print("noise:", req.noise, " is less than now:", now)
        return False
    new_md5 = md5()
    new_md5.update(req.tid.encode())
    new_md5.update(req.method.encode())
    new_md5.update(req.symbol.encode())
    noise = "%d" % req.noise
    new_md5.update(noise.encode())
    new_md5.update(glb_salt.encode())
    salt = base64.encodestring(new_md5.digest()).decode().strip()
    if salt == req.salt:
        """"""
        return True
    print("old slat:", req.salt, " is not equal to:", salt)


@app.on_event("startup")
def startup_event():
    signal.signal(signal.SIGINT, stop_server)


@app.post("/api/quantify/sync")
async def syncAction(req: QuantifyRequest) -> CBResponse:
    if not verifyReq(req):
        """"""
        rsp = CBResponse(symbol=req.symbol, name=req.name, tid=req.tid, status=400,
                         msg="Bad Request", action=dto.NONE_ACTION, day=GetCurDay())
        return rsp
    rsp = syncActor(req)
    return CopyRsp(req, rsp)


@app.post("/api/quantify/async")
async def asyncAction(req: QuantifyRequest) -> Response:
    if not verifyReq(req):
        """"""
        rsp = Response(symbol=req.symbol, tid=req.tid, status=400, msg="Bad Request")
        return rsp
    rsp = actor.asyncActor(req)
    return rsp
